package com.htu.courseService.websocket.system.handler;

import com.htu.courseService.websocket.chat.enums.ChatReplayEnum;
import com.htu.courseService.websocket.config.NettyConfig;
import com.htu.courseService.websocket.config.SocketMsg;
import com.htu.courseService.websocket.config.SocketUtil;
import com.htu.courseService.websocket.system.enums.ServerOperationEnum;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.stereotype.Component;

/**
 * Created By JNNarrator on 2024/9/21 23:03
 * email: jiangn09@chinatelecom.cn
 */
@Component("connect")
public class  ConnectHandler implements SystemHandler {
	@Override
	public void handle(SocketMsg<?> socketMsg, ChannelHandlerContext ctx) {
		// 获取用户ID,关联channel
		String uid = socketMsg.getAuthToken();
		if (NettyConfig.getChannelMap().containsKey(uid)) {
			Channel channel = NettyConfig.getChannelMap().get(uid);
			SocketMsg<Object> build = SocketMsg.build(ChatReplayEnum.USERID_EXIST);
			SocketUtil.channel(channel).sendMsgChannel(build);
			return;
		}
		NettyConfig.getChannelMap().put(uid, ctx.channel());
		// 将用户ID作为自定义属性加入到channel中，方便随时channel中获取用户ID
		AttributeKey<String> key = AttributeKey.valueOf("userId");
		ctx.channel().attr(key).setIfAbsent(uid);
		SocketUtil.ctx(ctx).sendMsg(SocketMsg.build(ServerOperationEnum.CONNECT_SUCCESS_REPLAY));
	}
}
